package io.dshubs.archives.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import io.dshubs.archives.dao.ArchiveBaseClassMapper;
import io.dshubs.archives.dao.ArchiveUsingRecordsMapper;
import io.dshubs.archives.entity.ArchiveBaseCategory;
import io.dshubs.archives.entity.ArchiveBaseInfo;
import io.dshubs.archives.entity.ArchiveUsingRecords;
import io.dshubs.archives.service.ArchiveBaseCategoryService;
import io.dshubs.archives.service.ArchiveUsingRecordsService;
import io.dshubs.commons.mybatis.enums.DelFlagEnum;
import io.dshubs.commons.mybatis.service.impl.BaseServiceImpl;
import io.dshubs.commons.security.user.SecurityUser;
import io.dshubs.commons.security.user.UserDetail;
import io.dshubs.commons.tools.constant.Constant;
import io.dshubs.commons.tools.enums.SuperAdminEnum;
import io.dshubs.commons.tools.exception.RenException;
import io.dshubs.commons.tools.page.PageData;
import io.dshubs.commons.tools.utils.Result;
import io.dshubs.dto.SysDeptDTO;
import io.dshubs.dto.SysTenantDTO;
import io.dshubs.feign.SysFeignClient;
import io.dshubs.feign.TenantFeignClient;
import org.apache.commons.collections4.CollectionUtils;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.List;
import java.util.Map;
import java.util.stream.Collector;
import java.util.stream.Collectors;

/**
 * <p>
 * 档案利用记录表 服务实现类
 * </p>
 *
 * @author tan
 * @since 2021-08-27
 */
@Service
public class ArchiveUsingRecordsServiceImpl extends BaseServiceImpl<ArchiveUsingRecordsMapper, ArchiveUsingRecords> implements ArchiveUsingRecordsService {

    @Autowired
    private ArchiveBaseClassMapper archiveBaseClassMapper;

    @Autowired
    private ArchiveBaseCategoryService archiveBaseCategoryService;


    @Autowired
    private TenantFeignClient tenantFeignClient;

    @Override
    public PageData<ArchiveUsingRecords> page(Map<String, Object> params) {
        IPage<ArchiveUsingRecords> page = baseDao.selectPage(
                getPage(params, Constant.CREATE_DATE, false),
                getWrapper(params)
        );
        PageData<ArchiveUsingRecords> pageData = getPageData(page, ArchiveUsingRecords.class);
        List<ArchiveUsingRecords> list = pageData.getList();
        if(list.size() > 0) {
           list.forEach(item->{
               SysTenantDTO data = tenantFeignClient.getTenantByCode(item.getUseTenantCode()).getData();
               item.setUseTenantName(data == null ? null:data.getTenantName());
               ArchiveBaseCategory baseCategory = archiveBaseClassMapper.selectById(item.getCategoryId());
               item.setCategoryName(baseCategory == null ? null : baseCategory.getName());
               SysTenantDTO sysTenantDTO = tenantFeignClient.getTenantByCode(item.getTenantCode()).getData();
               item.setTenantName(sysTenantDTO == null ? null:sysTenantDTO.getTenantName());
           });
        }

        return pageData;
    }

    private QueryWrapper<ArchiveUsingRecords> getWrapper(Map<String, Object> params){
        QueryWrapper<ArchiveUsingRecords> wrapper = new QueryWrapper<>();
        List<Long> ids = archiveBaseCategoryService.getArchiveBaseCategoryId();
        String proposer = (String)params.get("proposer");
        String fileNumber = (String)params.get("fileNumber");
        String title = (String)params.get("title");
        String categoryName = (String)params.get("categoryName");
        String useWay = (String)params.get("useWay");
        String predictDataBegin = (String)params.get("predictDataBegin");
        String predictDataEnd = (String)params.get("predictDataEnd");
        if(StringUtils.isNotEmpty(categoryName)) {
            List<ArchiveBaseCategory> list = archiveBaseClassMapper.selectList(new QueryWrapper<ArchiveBaseCategory>().like("name", categoryName)
                    .in(CollectionUtils.isNotEmpty(ids),"category_id",ids));
            wrapper.in(CollectionUtils.isNotEmpty(ids),"category_id",list.stream().map(ArchiveBaseCategory::getId).collect(Collectors.toList()));
        } else {
            wrapper.in(CollectionUtils.isNotEmpty(ids),"category_id",ids);
        }

        wrapper.eq(Constant.DEL_FLAG, DelFlagEnum.NORMAL.value());
        wrapper.like(StringUtils.isNotBlank(proposer), "name", proposer);
        wrapper.eq(StringUtils.isNotBlank(fileNumber),"file_number",fileNumber);
        wrapper.like(StringUtils.isNotBlank(title),"title",title);
        wrapper.eq(StringUtils.isNotBlank(useWay),"use_way",useWay);
        wrapper.ge(StringUtils.isNotBlank(predictDataBegin),"predict_data",predictDataBegin);
        wrapper.le(StringUtils.isNotBlank(predictDataEnd),"predict_data",predictDataEnd);
        UserDetail user = SecurityUser.getUser();
        if(user.getSuperAdmin() != SuperAdminEnum.YES.value()) {
            wrapper.eq("tenant_code",user.getTenantCode());
        }
        return wrapper;
    }

    @Override
    public void giveBack(List<String> ids) {
        if(CollectionUtils.isNotEmpty(ids)) {
            throw new RenException("id不能为空");
        }
        List<ArchiveUsingRecords> usingRecords = this.baseDao.selectBatchIds(ids);
        usingRecords.forEach(item->{
            item.setReturnDate(new Date());
            item.setUseState("1");
            this.baseDao.updateById(item);
        });

    }
}
